<template>
	<div>
        <!-- 操作按钮 -->
        <div class="operatBtnWrapper">
            <button class="operatBtn marR5" @click.stop="edit('form')" :disabled="!isFormOk" :class="{notAllowed:!isFormOk}">确认修改</button>
            <button class="operatBtn marR5" type="reset" @click.stop="resetForm('form')">清除内容</button>
            <!-- <button class="operatBtn" @click.stop="returnBack">返回上一页</button> -->
        </div>
        <!-- 表单 -->
		<el-form ref="form" :model="form" :rules="rules" class="paddLR20 marT10" :inline="true" label-width="80px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model.trim="form.name" class="inputTxtWrapper" maxlength="9" @input.stop.native="watchFrmChange"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="上级类别" prop="selectedArr" class="inputTxtWrapper">
                        <el-cascader
                            expand-trigger="hover"
                            :options="treeList"
                            v-model="form.selectedArr"
                            change-on-select
                            @change="watchFrmChange">
                        </el-cascader>
                    </el-form-item>
                </el-col>
            </el-row>
		</el-form>
	</div>
</template>
<script>
  import http from '../../../../assets/js/http'
  import _g from '@/assets/js/global'
 

  export default {
    data() {
      return {
        isFormOk:false,//表单默认没有通过校验

        treeList : [],//    组织架构树

        form: {
          name: '',
          selectedArr : [],//    上级分类
        },
        rules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' }
          ],
          selectedArr: [
            { required: true, message: '请选择组织架构', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
    /* 侦听基本表单改变与校验是否通过 */ 
    watchFrmChange(){
        this.isFormOk = true
    },
      /* 重置表单 */
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      /* 确认修改 */
      edit(form) {
        const that = this


        let name = ''//..组织架构名字
        let id = ''//..所属组织架构id
        const structId = that.structId

        let strPath = ''

        let selectedArr = JSON.parse(JSON.stringify(that.form.selectedArr))
       
        // const userId = Cookies.get('userId')
        this.$refs[form].validate((valid) => {                                              //  表单校验成功
          if (valid) {

              name = that.form.name
              id = that.form.selectedArr[that.form.selectedArr.length - 1]
              if(selectedArr.indexOf(0) > -1){
                  selectedArr.splice(0,1)
              }
            if(JSON.stringify(selectedArr) === JSON.stringify([1,1])){
                selectedArr = [1]
            }
              console.log(selectedArr)
              strPath = selectedArr.join(',')
console.log(strPath)
              that.$confirm('是否确认修改?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                  center: true
              }).then(() => {
                    _g.showLoading('提交中')
                    that.apiPost('admin/infiniteLevelStructure/edit', {id,name,structId,strPath}).then((res) => {
                         _g.showLoading().close()
                         if(typeof res === 'string'){
                            res = JSON.parse(res)
                          }
                        if (res.code != 200) {
                          that.handleError(res)
                        } else {
                          if(res.data.isSuccess === 0){             //  成功
                              _g.toastMsg("success", res.message)
                              that.$router.push('/admin/structures/list')

                          }else if(res.data.isSuccess === 1){
                              _g.toastMsg("error", res.message)
                          }else if(res.data.isSuccess === 2 || res.data.isSuccess === 3){
                              _g.toastMsg("warning", res.message)
                          }
                        }
                    })
              }).catch(() => {});
          }
        })
      },

      /* 递归排除当前子类 */
      /* 递归获取子类id数组 */
        getChildrenIdsArr(children,structId){
            for(let item of children){
                if(item.value == structId){
                    item['disabled'] = true
                    // children = children.filter((val) => val.value !== structId)
                }
                if(item.children !== undefined){
                     this.getChildrenIdsArr(item.children,structId)
                }
            }
        },
    
        /* 查询无限级组织架构 */
      queryInfiniteLevelStructure() {
        _g.showLoading('职位加载中');
        const that = this
        const structId = this.structId

        let result = []

        that.apiPost('admin/infiniteLevelStructure/queryInfiniteLevelStructure').then((res) => {
            _g.showLoading().close()
            if(typeof res === 'string'){
                res = JSON.parse(res)
            }
            if (res.code != 200) {
                that.handleError(res)
            } else {
                if(res.data.isSuccess === 0){
                    result = res.data.result
                    that.getChildrenIdsArr(result,structId)
                    that.treeList = result
                }else if(res.data.isSuccess === 1){
                    _g.toastMsg("error", res.message)
                     that.$router.push('/admin/structures/list')
                }
            }
        })
      },
    },
    created() {
        this.structId = this.$route.query.structId
        this.queryInfiniteLevelStructure()
        let structIdsStr = this.$route.query.structIdsStr
        this.form.selectedArr = structIdsStr.split(',').map(item =>  +item);  
                                                                                    
        this.form.name = this.$route.query.name

        this.structId = (+this.$route.query.structId)
    },
    mixins: [http]
  }
</script>